{% extends "前端电脑版/template.html" %}

{% block title %}用户列表{% endblock %}

{% include '前端电脑版/公共样式配置/CSS总样式.html' %}

{% block css %}
<style>
    .avatar-initial {
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 500;
        color: #fff;
        background-color: #696cff;
    }
    .table > :not(caption) > * > * {
        padding: 1rem;
    }
    .btn-icon {
        padding: 0.5rem;
        border-radius: 0.375rem;
    }
    .btn-icon:hover {
        background-color: rgba(0,0,0,0.05);
    }
</style>
{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <!-- 页面标题 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="fw-bold py-3 mb-0">
            <span class="text-muted fw-light">用户管理 /</span> 用户列表
        </h4>
        <div class="d-flex gap-2">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#searchModal">
                <i class='bx bx-search-alt me-1'></i>高级搜索
            </button>
            <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addUserModal">
                <i class='bx bx-user-plus me-1'></i>添加用户
            </button>
        </div>
    </div>

    <!-- 搜索栏 -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-4">
                    <div class="input-group">
                        <span class="input-group-text"><i class='bx bx-search'></i></span>
                        <input type="text" class="form-control" id="searchInput" placeholder="搜索用户名或账号...">
                    </div>
                </div>
                <div class="col-md-2">
                    <select class="form-select" id="sortBy">
                        <option value="create_time">创建时间</option>
                        <option value="update_time">更新时间</option>
                        <option value="user_name">用户名</option>
                        <option value="account">账号</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <select class="form-select" id="sortOrder">
                        <option value="desc">降序</option>
                        <option value="asc">升序</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <select class="form-select" id="pageSize">
                        <option value="10">10条/页</option>
                        <option value="20">20条/页</option>
                        <option value="50">50条/页</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="button" class="btn btn-primary w-100" onclick="searchUsers()">
                        <i class='bx bx-filter-alt me-1'></i>筛选
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 用户列表 -->
    <div class="card">
        <div class="table-responsive text-nowrap">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>用户名</th>
                        <th>账号</th>
                        <th>创建时间</th>
                        <th>更新时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="userTableBody">
                    <!-- 用户数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
        <!-- 分页 -->
        <div class="card-footer">
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center mb-0" id="pagination">
                    <!-- 分页将通过JavaScript动态加载 -->
                </ul>
            </nav>
        </div>
    </div>
</div>

<!-- 高级搜索模态框 -->
<div class="modal fade" id="searchModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">高级搜索</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="advancedSearchForm">
                    <div class="mb-3">
                        <label class="form-label">时间范围</label>
                        <div class="row g-2">
                            <div class="col-6">
                                <input type="datetime-local" class="form-control" id="startTime">
                            </div>
                            <div class="col-6">
                                <input type="datetime-local" class="form-control" id="endTime">
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="advancedSearch()">搜索</button>
            </div>
        </div>
    </div>
</div>

<!-- 添加用户模态框 -->
<div class="modal fade" id="addUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addUserForm">
                    <div class="mb-3">
                        <label class="form-label">账号</label>
                        <input type="text" class="form-control" name="account" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">密码</label>
                        <input type="password" class="form-control" name="password" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addUser()">添加</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
let currentPage = 1;
let currentPageSize = 10;
let userDetails = {}; // 存储用户详情

// 配置axios默认值
axios.defaults.headers.common['X-USER-ID'] = '{{ request.user.user_id }}';

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    loadUsers();
    setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
    // 搜索框回车事件
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchUsers();
        }
    });

    // 每页显示数量变化事件
    document.getElementById('pageSize').addEventListener('change', function() {
        currentPageSize = parseInt(this.value);
        currentPage = 1;
        loadUsers();
    });
}

// 加载用户列表
function loadUsers() {
    const search = document.getElementById('searchInput').value;
    const sortBy = document.getElementById('sortBy').value;
    const sortOrder = document.getElementById('sortOrder').value;
    const startTime = document.getElementById('startTime')?.value;
    const endTime = document.getElementById('endTime')?.value;

    let url = `/api/user/user_list/?page=${currentPage}&page_size=${currentPageSize}`;
    if (search) url += `&search=${encodeURIComponent(search)}`;
    if (sortBy) url += `&sort_by=${sortBy}`;
    if (sortOrder) url += `&sort_order=${sortOrder}`;
    if (startTime) url += `&start_time=${encodeURIComponent(startTime)}`;
    if (endTime) url += `&end_time=${encodeURIComponent(endTime)}`;

    axios.get(url)
        .then(response => {
            const data = response.data;
            if (data.code === 0) {
                renderUserTable(data.data.users);
                renderPagination(data.data.pagination);
            } else {
                showToast('error', '获取用户列表失败', data.msg);
            }
        })
        .catch(error => {
            showToast('error', '系统错误', error.message);
        });
}

// 渲染用户表格
function renderUserTable(users) {
    const tbody = document.getElementById('userTableBody');
    tbody.innerHTML = '';
    userDetails = {}; // 清空之前的用户详情

    users.forEach(user => {
        userDetails[user.user_id] = user; // 保存用户详情
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>
                <div class="d-flex align-items-center">
                    <div class="avatar avatar-sm me-2">
                        <span class="avatar-initial rounded-circle bg-label-primary">
                            ${user.user_name.charAt(0).toUpperCase()}
                        </span>
                    </div>
                    <div class="fw-medium">${user.user_name}</div>
                </div>
            </td>
            <td>${user.account}</td>
            <td>${user.create_time}</td>
            <td>${user.update_time}</td>
            <td>
                <div class="d-inline-block">
                    <button class="btn btn-sm btn-icon" onclick="viewUser('${user.user_id}')">
                        <i class='bx bx-show text-primary'></i>
                    </button>
                </div>
            </td>
        `;
        tbody.appendChild(tr);
    });
}

// 渲染分页
function renderPagination(pagination) {
    const paginationElement = document.getElementById('pagination');
    paginationElement.innerHTML = '';

    // 上一页
    const prevLi = document.createElement('li');
    prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
    prevLi.innerHTML = `
        <a class="page-link" href="javascript:void(0);" onclick="changePage(${currentPage - 1})">
            <i class='bx bx-chevron-left'></i>
        </a>
    `;
    paginationElement.appendChild(prevLi);

    // 页码
    for (let i = 1; i <= pagination.total_pages; i++) {
        const li = document.createElement('li');
        li.className = `page-item ${currentPage === i ? 'active' : ''}`;
        li.innerHTML = `
            <a class="page-link" href="javascript:void(0);" onclick="changePage(${i})">${i}</a>
        `;
        paginationElement.appendChild(li);
    }

    // 下一页
    const nextLi = document.createElement('li');
    nextLi.className = `page-item ${currentPage === pagination.total_pages ? 'disabled' : ''}`;
    nextLi.innerHTML = `
        <a class="page-link" href="javascript:void(0);" onclick="changePage(${currentPage + 1})">
            <i class='bx bx-chevron-right'></i>
        </a>
    `;
    paginationElement.appendChild(nextLi);
}

// 切换页码
function changePage(page) {
    currentPage = page;
    loadUsers();
}

// 搜索用户
function searchUsers() {
    currentPage = 1;
    loadUsers();
}

// 高级搜索
function advancedSearch() {
    currentPage = 1;
    loadUsers();
    $('#searchModal').modal('hide');
}

// 添加用户
function addUser() {
    const form = document.getElementById('addUserForm');
    const formData = new FormData(form);
    // 用URLSearchParams编码
    const params = new URLSearchParams();
    for (const [key, value] of formData.entries()) {
        params.append(key, value);
    }
    axios.post('/api/user/create/', params, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    .then(response => {
        const data = response.data;
        if (data.code === 0) {
            showToast('success', '添加成功', '用户已成功添加');
            $('#addUserModal').modal('hide');
            form.reset();
            // 立即刷新用户列表
            loadUsers();
        } else {
            showToast('error', '添加失败', data.msg);
        }
    })
    .catch(error => {
        showToast('error', '系统错误', error.message);
    });
}

// 查看用户
function viewUser(userId) {
    const user = userDetails[userId];
    if (!user) {
        showToast('获取用户信息失败', 'error');
        return;
    }

    // 创建并显示用户详情模态框
    const modalHtml = `
        <div class="modal fade" id="viewUserModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">用户详情</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="d-flex align-items-center mb-4">
                            <div class="avatar avatar-lg me-3">
                                <span class="avatar-initial rounded-circle bg-label-primary">
                                    ${user.user_name.charAt(0).toUpperCase()}
                                </span>
                            </div>
                            <div>
                                <h5 class="mb-1" id="userNameDisplay">${user.user_name}
                                    <button class="btn btn-sm btn-link text-primary p-0 ms-2" onclick="showEditUserNameModal('${user.user_name}')" title="修改用户名">
                                        <i class='bx bx-edit'></i>
                                    </button>
                                </h5>
                                <span class="text-muted">${user.account}</span>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12 mb-3">
                                <small class="text-muted d-block">用户ID</small>
                                <span class="fw-medium">${user.user_id}</span>
                            </div>
                            <div class="col-6 mb-3">
                                <small class="text-muted d-block">创建时间</small>
                                <span class="fw-medium">${user.create_time}</span>
                            </div>
                            <div class="col-6 mb-3">
                                <small class="text-muted d-block">更新时间</small>
                                <span class="fw-medium">${user.update_time}</span>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- 修改用户名模态框 -->
        <div class="modal fade" id="editUserNameModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">修改用户名</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form id="editUserNameForm">
                            <div class="mb-3">
                                <label class="form-label">新用户名</label>
                                <input type="text" class="form-control" name="user_name" id="editUserNameInput" value="${user.user_name}" required minlength="2" maxlength="20">
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="updateUserName()">保存</button>
                    </div>
                </div>
            </div>
        </div>
    `;

    // 移除可能存在的旧模态框
    const oldModal = document.getElementById('viewUserModal');
    if (oldModal) {
        oldModal.remove();
    }
    const oldEditModal = document.getElementById('editUserNameModal');
    if (oldEditModal) {
        oldEditModal.remove();
    }

    // 添加新模态框到页面
    const modalContainer = document.createElement('div');
    modalContainer.innerHTML = modalHtml;
    document.body.appendChild(modalContainer);

    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('viewUserModal'));
    modal.show();

    // 监听模态框关闭事件，移除DOM
    document.getElementById('viewUserModal').addEventListener('hidden.bs.modal', function () {
        this.remove();
    });
}

// 显示修改用户名模态框
function showEditUserNameModal(currentName) {
    document.getElementById('editUserNameInput').value = currentName;
    const modal = new bootstrap.Modal(document.getElementById('editUserNameModal'));
    modal.show();
}

// 修改用户名
function updateUserName() {
    const input = document.getElementById('editUserNameInput');
    const user_name = input.value.trim();
    if (user_name.length < 2 || user_name.length > 20) {
        showToast('error', '用户名长度需在2-20个字符之间');
        return;
    }
    const params = new URLSearchParams();
    params.append('user_name', user_name);
    axios.post('/api/user/update_user_name/', params, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    .then(response => {
        const data = response.data;
        if (data.code === 0) {
            showToast('success', '修改成功', '用户名已更新');
            // 关闭模态框
            $('#editUserNameModal').modal('hide');
            // 刷新用户列表
            loadUsers();
            // 同步更新详情页用户名
            document.getElementById('userNameDisplay').childNodes[0].nodeValue = user_name;
        } else {
            showToast('error', '修改失败', data.msg);
        }
    })
    .catch(error => {
        showToast('error', '系统错误', error.message);
    });
}
</script>
{% endblock %}

{% block nav_left %}
{% include "前端电脑版/components/左侧导航栏.html" %}
{% endblock %}

{% block NavBar %}
{% endblock %}

{% include '前端电脑版/公共样式配置/JS总样式.html' %}

{% block footer %}
    {% include "前端电脑版/components/Footer.html" %}
{% endblock %}